// 获取应用实例
const app = getApp();

Page({
  data: {
    examInfo: {
      title: '',
      duration: 0,
      questionCount: 0,
      totalScore: 0
    },
    historyList: []
  },

  onLoad() {
    this.loadPageData();
  },

  onPullDownRefresh() {
    this.loadPageData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载页面数据
  loadPageData() {
    return Promise.all([
      this.loadExamInfo(),
      this.loadHistoryList()
    ]);
  },

  // 加载考试信息
  loadExamInfo() {
    return app.request({
      url: '/exam/info',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          examInfo: res.data
        });
      }
    }).catch(() => {
      app.showError('获取考试信息失败');
    });
  },

  // 加载历史记录
  loadHistoryList() {
    return app.request({
      url: '/exam/history',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          historyList: res.data.list
        });
      }
    }).catch(() => {
      app.showError('获取历史记录失败');
    });
  },

  // 开始考试
  startExam() {
    wx.showModal({
      title: '确认开始',
      content: '开始考试后将计时，是否确认开始？',
      success: (res) => {
        if (res.confirm) {
          app.request({
            url: '/exam/start',
            method: 'POST'
          }).then(res => {
            if (res.code === 0) {
              wx.navigateTo({
                url: `/pages/exam-question/exam-question?id=${res.data.examId}`
              });
            }
          }).catch(() => {
            app.showError('开始考试失败');
          });
        }
      }
    });
  },

  // 查看历史
  viewHistory() {
    // 历史记录已在页面中显示，无需额外操作
  },

  // 查看考试结果
  viewResult(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/exam-result/exam-result?id=${id}`
    });
  }
}); 